import json
import os

from dataProcess.CategoryStatistical import CategoryStatistical
from dataProcess.TimeStatistical import TimeStatistical
# bean实体类
from .models import User
from .models import Meta

# dao数据访问层
from .dao import Mysql_Static_Factory
from .dao import UserDaoImpl


# 这一句代码——大宝贝：多个自定义类存与字典中，如何把该字典转换为JSON
# json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, (User, Meta)) else None, ensure_ascii=False)

class UserService:
    """提供User功能服务"""

    def login(self, username: str, password: str):
        """通过用户ID查询用户信息
            @param 用户名,
            @param 密码,
            @return {User+Meta} 字典数据"""
        user_id = UserDaoImpl().selectByNamePWD(username, password)
        data = UserDaoImpl().selectByID(user_id)

        meta = Meta("登录成功", 200)
        metaFaild = Meta("登录失败", 400)

        response = {
            'data': data,
            'meta': meta if data is not None else metaFaild
        }

        json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, (User, Meta)) else None,
                              ensure_ascii=False)

        print(json_str)

        return (json_str)

    def register(self, username: str, password: str, user_picture: str, types: str):
        """添加新用户
                    @param 用户名,
                    @param 密码,
                    @param 用户头像,
                    @param 用户类型,
                    @return {User+Meta} 字典数据"""

        # 实例化用户类
        user = User(0, username, password, 1, 'vip', types, 1000, user_picture, "这个人很懒，什么都没有留下")
        print(user.__str__)
        userDaoImpl = UserDaoImpl()

        isok = False
        # 尝试添加用户
        try:
            isok = userDaoImpl.inserUser(user)
        except Exception as e:
            print('创建用户失败')
            print(e)

        meta = Meta

        # 创建成功，收集用户数据准备返回给前端
        if isok:
            user_id = userDaoImpl.selectByNamePWD(username, password)
            data = userDaoImpl.selectByID(user_id)
            meta = Meta('添加用户成功', 200)

            response = {
                'data': data,
                'meta': meta
            }

            json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, (User, Meta)) else None,
                                  ensure_ascii=False)
            return json_str
        # 创建失败，制作假数据，并且设置meta
        else:
            meta = Meta('添加用户失败', 400)
            response = {
                'fackUser': User,
                'meta': meta
            }
            json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, (User, Meta)) else None,
                                  ensure_ascii=False)
            return json_str


class TimeRankService:
    def __init__(self):
        # 当前脚本的绝对路径
        self.my_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        self.deep_articles = self.my_BASE_DIR + '/static/csv_collect/deep_articles.csv'

    def getTimeRank(self):
        ts = TimeStatistical()
        print(self.deep_articles)
        data = ts.statistical(csv_path=self.deep_articles)
        meta = Meta("查找时间分布成功", 200)
        metaFaild = Meta("查找时间分布失败", 400)

        response = {
            'data': data,
            'meta': meta if data is not None else metaFaild
        }

        json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, (User, Meta)) else None,
                              ensure_ascii=False)

        # print(json_str)

        return (json_str)


class CategoryService:

    def getCategory(self):
        cs = CategoryStatistical()
        data = cs.run()

        meta = Meta("查找文章类别分布成功", 200)
        metaFaild = Meta("查找文章类别分布失败", 400)

        response = {
            'data': data,
            'meta': meta if data is not None else metaFaild
        }

        json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, (User, Meta)) else None,
                              ensure_ascii=False)

        # print(json_str)

        return json_str


'''完美分层实在太痛苦了,肝不动了,其他的全部一股脑写models.py里面了,既当control又当service,哪天肝和腰养好了再来继续分离'''
